<?php
  final class URI
  {
    private static $url = '';
    private static $isIIS = false;
    private static $segments = array();
    private static $params = array();
    private static $queryString = '';
    private static $protocol;

    public static function init()
    {
      self::$protocol = Config::getProtocol();
      self::initURL();
    }
 
    private static function initURL()
    {      
      $isIIS = false;
      
      if (!isset($_SERVER['REQUEST_URI']))
      {
        $isIIS = true;

        $_SERVER['REQUEST_URI'] = substr($_SERVER['PHP_SELF'],1 );

        if (isset($_SERVER['QUERY_STRING']) AND $_SERVER['QUERY_STRING'] != "")
          $_SERVER['REQUEST_URI'] .= '?'.$_SERVER['QUERY_STRING'];

        if( stristr($_SERVER['REQUEST_URI'], '404;') )
        {
          $split404 = explode('404;', $_SERVER['REQUEST_URI']);
          $_SERVER['REQUEST_URI'] = $split404[1];
        }
      }
      
      if ($isIIS)
        $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_HOST'].'/';

      if( !stristr($_SERVER['REQUEST_URI'], '://') )
        $requestURL = self::$protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
      else
        $requestURL = $_SERVER['REQUEST_URI'];

      $requestURL = str_replace(array('\\','\\\\'), array('/'), $requestURL);

      if( !stristr($requestURL, Config::$siteURL) )
      {
        if( stristr($requestURL, 'index.php') )
        {
          list($dir, $requestURL) = explode('index.php/', $requestURL);
          $requestURL = Config::$siteURL.'index.php/'.$requestURL;
        }
      }

      $requestURL = XSS::cleanString($requestURL, false, array(), true);
      
      self::$url = $requestURL;
      self::$isIIS = $isIIS;
      
      self::initSegments();
      self::initParams();
      self::initQueryString();
    }
    
    private static function initParams()
    {
      $segments = self::getSegments();

      if( isset($segments[0]) && isset($segments[1]) )
      {
        unset( $segments[0] );
        unset( $segments[1] );
      }

      if( $segments['query'] )
        unset( $segments['query'] );

      $params = array();

      foreach ($segments as $key=>$value)
      {
        if(is_numeric($key))
          $params[] = $value;
        else
          $params[$key] = $value;
      }

      foreach ($params as $key=>$value)
      {
      	if($value == '')
          unset($params[$key]);
      }

      self::$params = $params;
    }
    
    private static function initSegments()
    {
      $uri = str_replace(Config::$siteURL , '', self::getURL());

      $parsedUrl = parse_url($uri);

      $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
      $query =  self::getQuery();

      $segments = explode('/', $path);
      $lastSegment = $segments[count($segments)-1];

      $params = array();


      foreach ($segments as $key=>$value)
      {
      	if(($value !== '') && ($value !== 'index.php'))
      	 $params[] = $value;
        else if($value !== 'index.php')
          break;
      }

      $params['query'] = $query;

      self::$segments = $params;
    }
    
    private static function initQueryString()
    {
      $segments = self::getSegments();
      
      if( isset($segments['query']) && ($segments['query'] !=''))
        self::$queryString = '?'.$segments['query'];
    }
    
    public static function getURL($removeQueryString = false)
    {
      if(($removeQueryString) && (stristr(self::$url, '?') ))
        list(self::$url) = explode('?', self::$url);

      return self::$url;
    }
    
    public static function removeIndexPHP($url)
    {
      return str_ireplace('index.php/','',$url);
    }
    
    public static function getSegments()
    {      
      return self::$segments;
    }
    
    private static function getQuery()
    {
      $queryStr = '';
      
      foreach (Get::getAll() as $key=>$value)
        $queryStr .= $key.'='.$value.'&';
        
      return $queryStr;
    }
    
    public static function getParams()
    {
      return self::$params;
    }
    
    public static function getParam($index)
    {
      $params = self::getParams();
      
      if( isset($params[$index]) )
        return $params[$index];
        
      return '';
    }

    public static function getQueryString()
    {
      return self::$queryString;
    }
    
    public static function getSegmentsFromString($url, $directorySeperator = '')
    {
      if($directorySeperator == '')
        $directorySeperator = Config::$directorySeperator;

      return explode( $directorySeperator ,  $url );
    }
    
    public static function getSegment($index)
    {
      $segments = self::getSegments();
      
      if(count($segments) <= $index)
        return '';
      
      if( isset($segments[$index]) )
        return $segments[$index];
      else
        return '';
    }
    
    public static function convertSiteURLToSiteDir($url)
    {
      return str_ireplace( Config::$siteURL, Config::$siteDir, $url);
    }
    
    public static function getParamsAsURI()
    {
      $segments = self::getParams();

      if( count($segments) == 0 )
        return '';
      
      $uri = '';

      foreach ($segments as $key=>$value)
      {
        $uri .= $value;

        if(isset($segments[count($segments)-1]) && ($segments[count($segments)-1] != $value ))
          $uri .= '/';
      }

      return $uri;
    }
    
    public static function getSegementsAsURI()
    {
      $segments = self::getSegments();
      $uri = '';

      $counter = 0;
      foreach ($segments as $key=>$value)
      {
        $uri .= $value;
        
        if($counter < count($segments)-2 )
          $uri .= '/';

        $counter++;
      }

      return $uri;
    }
    
    public static function getResponse($url)
    {
      $segments = parse_url($url);

      $errno = '';
      $errstr = '';
      $content = '';
      $header = "not yet";
      $path='/';
      $query = '';

      if(isset($segments['path']))
        $path = $segments['path'];

      if(isset($segments['query']))
        $query = '?'.$segments['query'];

      $fp = fsockopen($segments['host'], 80, $errno, $errstr, 30);
      if (!$fp) {
          echo "$errstr ($errno)<br />\n";
      } else {
          $out = "GET $path$query HTTP/1.1\r\n";
          $out .= "Host: ".$segments['host']."\r\n";
          $out .= "Connection: Close\r\n\r\n";
          fwrite($fp, $out);
          while (!feof($fp)) {
              $content .= fgets($fp, 128);
          }
      }
      fclose($fp);

      $content = '<base href='.$segments['scheme'].'://'.$segments['host'].$path.'">'.substr($content, strpos($content, '<'), strlen($content) );
      return $content;
    }

  }
?>
